import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';


// 动态导入
const modules: Record<string, any> = import.meta.glob(['./modules/*.ts'], {
  eager: true,
})
// 配置路由
const routes: Array<RouteRecordRaw> = [];

const otherRoute: Array<RouteRecordRaw> = [
  {
    path: '',
    redirect: '/'
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/404/404.vue'),
    meta: {
      title: '404',
      icon: '404'
    },
    children: []
  }

]


Object.keys(modules).forEach((key) => {
  const module = modules[key].default
  routes.push(module)
})
routes.push(...otherRoute)

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 路由守卫
router.beforeEach((_to, _from, next) => {
  NProgress.start()
  // 判断是否有对应路由
  const isExist = router.hasRoute(_to.name as string)
  if (!isExist) {
    return next('/404')
  }

  // 登录逻辑
  // const token = sessionStorage.getItem('token')
  // const userIsLogin = !!token
  // if(userIsLogin || _to.path === '/login') {
  next()
  // } else {
  //   next('/login')
  // }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
